package com.ld.businesscard_manage.controller.user;

import com.ld.businesscard_manage.bean.User;
import com.ld.businesscard_manage.service.UserService;
import com.ld.businesscard_manage.service.impl.UserServiceImpl;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginController extends HttpServlet {
	private UserService userService = new UserServiceImpl();
	public void selectUserByNameAndPwd(HttpServletRequest request, HttpServletResponse response){
		String username = request.getParameter("username");
		String password = DigestUtils.md5Hex(request.getParameter("password"));
		String verCode = request.getParameter("verCode");
		if (!CaptchaUtil.ver(verCode, request)) {
			CaptchaUtil.clear(request);  // 清除session中的验证码
			try {
				response.sendRedirect("/index.jsp");
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}else {
			User user = userService.getUserByNameAndPsw(username, password);
			if (user == null) {
				try {
					response.sendRedirect("/index.jsp");
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			} else {
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				if (user.getStatus() == 0) {
					try {
						request.getRequestDispatcher("/home/application.jsp").forward(request, response);
					} catch (ServletException e) {
						throw new RuntimeException(e);
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				}
				if (user.getStatus() == 1) {
					try {
						request.getRequestDispatcher("/home/manage.jsp").forward(request, response);
					} catch (ServletException e) {
						throw new RuntimeException(e);
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				}
			}
		}

	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		selectUserByNameAndPwd(req,resp);
	}
}
